package org.pupil.rpc.router.routerImpl;

import org.pupil.rpc.common.ServiceMeta;
import org.pupil.rpc.config.RpcProperties;
import org.pupil.rpc.registry.RegistryService;
import org.pupil.rpc.router.LoadBalancer;
import org.pupil.rpc.router.ServiceMetaRes;
import org.pupil.rpc.spi.ExtensionLoader;

import java.util.List;
import java.util.Random;

/**
 * 随机负载均衡器
 */
public class RandomLoadBalancer implements LoadBalancer {

    private final Random random = new Random();

    @Override
    public ServiceMetaRes select(Object[] params, String serviceName) {
        // 获取注册中心
        RegistryService registryService = ExtensionLoader.getInstance().get(RpcProperties.getInstance().getRegisterType());
        List<ServiceMeta> discoveries = registryService.discoveries(serviceName);
        int size = discoveries.size();
        if (size == 0) {
            return null;
        }
        // 只有 1 个服务，不用随机
        if (size == 1) {
            final ServiceMeta curServiceMeta = discoveries.get(0);
            return ServiceMetaRes.build(curServiceMeta, discoveries);
        }
        final ServiceMeta curServiceMeta = discoveries.get(random.nextInt(size));
        return ServiceMetaRes.build(curServiceMeta, discoveries);
    }
}
